package lib.self.ex;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.Nullable;
import lib.self.LogMgr;
import lib.self.ex.interfaces.INetwork;
import lib.self.network.NetworkExecutor;
import lib.self.network.bean.NetworkListener;
import lib.self.network.bean.NetworkRequest;
import lib.self.network.bean.NetworkResponse;
import lib.self.network.error.NetError;

/**
 * description: Service基类
 * author: Steven Xiao
 * date: 2017/6/2
 */
public abstract class ServiceEx extends Service implements INetwork {

    protected final String TAG = getClass().getSimpleName();

    private NetworkExecutor mNetworkExecutor;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * http task part
     */

    public void exeNetworkRequest(int what, NetworkRequest request) {
        exeNetworkRequest(what, request, this);
    }

    public void exeNetworkRequest(int what, NetworkRequest request, NetworkListener listener) {
        if (mNetworkExecutor == null) {
            mNetworkExecutor = new NetworkExecutor(getClass().getName(), this);
        }
        mNetworkExecutor.execute(what, request, listener);
    }

    @Override
    public void cancelAllNetworkRequest() {
        if (mNetworkExecutor != null) {
            mNetworkExecutor.cancelAll();
        }
    }

    @Override
    public void cancelNetworkRequest(int tag) {
        if (mNetworkExecutor != null) {
            mNetworkExecutor.cancel(tag);
        }
    }

    @Override
    public Object onNetworkResponse(int id, NetworkResponse nr) {
        return null;
    }

    @Override
    public void onNetworkSuccess(int id, Object result) {
    }

    @Override
    public void onNetworkError(int id, NetError error) {
        LogMgr.d(TAG, "onNetworkError(): " + "what = [" + id + "], error = [" + error.message() + "]");
    }

    @Override
    public void onNetworkProgress(int id, float progress, long totalSize) {
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        cancelAllNetworkRequest();
        mNetworkExecutor = null;
    }
}
